
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.tools.bzip2.CBZip2InputStream;
import com.ice.tar.TarEntry;
import com.ice.tar.TarInputStream;
import java.util.Iterator;
/**
 * 
 * Iterator of a freedb.org file
 *
 */
public class Disc_Iter implements Iterator<String> {
	private int bytesLimit=81920000;
	private TarEntry tarEntry;
	private TarInputStream tis;
	private FileInputStream is;
	private InputStream bzis;
	String parentGenre="";
	
	public Disc_Iter(String tarFileName) throws IOException{
		 File f = new File(tarFileName);
	     this.is = new FileInputStream(f);
	     is.read();
	     is.read();
	     this.bzis  = new CBZip2InputStream(is);
	     this.tis = new TarInputStream(bzis);
	     tis.mark(this.bytesLimit);
	     this.tarEntry = tis.getNextEntry();
	}
	
	@Override
	public boolean hasNext() {
		return (this.tarEntry!=null);
	}
	
	public String next(){
		try{
			String result = "";
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			
			while ((tarEntry!=null)&&(tarEntry.isDirectory())){
					parentGenre=tarEntry.getName();
					tarEntry=tis.getNextEntry();
			}
			tis.copyEntryContents(baos);
			InputStream fin = new ByteArrayInputStream(baos.toByteArray());
			BufferedReader br = new BufferedReader(new InputStreamReader(fin));
			String line = null;
				while ((line = br.readLine()) != null){
					result+=line+'\n';					
				}
			
			br.close();
			fin.close();
			baos.close();
			tarEntry = tis.getNextEntry();
			result+="PARENT_GENRE:"+parentGenre+"@@@@@@@"+'\n';
			
			return result;
			} 
		
		catch (IOException e) 
			{ 
				return null;
			}
	}

	@Override
	public void remove() {
		// TODO Auto-generated method stub
		
	}
	
}
